﻿///version 3.8

var innerLayout = null;

var CDNname = ""
$.ajaxSetup({
    cache: false
});

function fixIECorner() {
    $(".ui-corner-top").corner("top 8px");
    $(".ui-corner-bottom").corner("bottom 8px");
    $(".ui-corner-all").corner("8px");
}

//load ajax to Holder
function switchPage(holder, url, showUrl, callback) {
    if ($(holder + ":animated")) {
		//show url
		var URL = "";
		if(showUrl) URL = '" '+ url + '"';
		///fix open in pane
		innerLayout = null;
		$(holder).height('auto');
		//clear dialog
		clearAllDialogMarkup();
		//fix ---del validate div
		$(".formErrorContent").parent().remove();
		//
		$(holder).fadeOut(200, function() {
		    $(this).show().html('<div class="openPage"><img src="' + CDNname + 'images/loading.gif" alt="loading" align="absmiddle"/>Opening page please wait' + URL + '...</div>').load(url, function() {
		        $(this).fadeIn(500, function() {
		            //fixIECorner();
		            //calback
		            if (callback) { eval(callback) };
		        });
		    });

		});
		
    }
}
//load ajax not animate
function loadPage(holder, url, showUrl, callback) {
	//show url
	var URL = "";
	if(showUrl) URL = '" '+ url + '"';
    ///fix open in pane
	innerLayout = null;
	$(holder).height('auto');
	//clear dialog
	clearAllDialogMarkup();
	//fix ---del validate div
	$(".formErrorContent").parent().remove();
	//
	$(holder).html('<div class="openPage" style="width:' + $(holder).width() + 'px;height:' + $(holder).height() + 'px"><img src="' + CDNname + 'images/loading.gif" alt="loading" align="absmiddle"/>Opening page please wait' + URL + '...</div>').load(url, function() {
	    $(this).show(5, function() {
	        //calback
	        //fixIECorner();
	        if (callback) { eval(callback) };
	    });
	});
}

//for load list as grid by post data
function loadListView(holder,url,data,callback){
	innerLayout = null;///fix open in pane
	$(holder).height('auto');
	
	$(holder).html('<div class="openPage" style="width:' + $(holder).width() + 'px;height:' + $(holder).height() + 'px"><img src="' + CDNname + 'images/loading.gif" alt="loading" align="absmiddle"/>Loading data please wait...</div>');
	
	if(data){
	    $.post(url, data, function(DATA) {
	        $(holder).html(DATA).show(5, function() {
	            //fixIECorner();
	            if (callback) { eval(callback) };
	        });
	    });
	}else{
	$(holder).load(url, function() {
	    $(this).show(5, function() {
	        //calback
	        //fixIECorner();
	        if (callback) { eval(callback) };
	    });
	});
	}
}

/* dialog control*/
function openDlgFrame(dlg, titleCaption, w, h, url, Modal, autoDIV, closeOther, closeCallback, openCallback) {
	
	var lastScroll = $(".ui-layout-center:first").scrollTop();
	
	if(autoDIV){
		if($("body").find("div#"+dlg).size() == 0){
			$("body").append('<div id="'+dlg+'"></div>');
		}
	}
    var dlgTemp = $('#' + dlg);
    if (!Modal) {
        Modal = false;
    }
    //clear all
    if (closeOther) {
        clearAllDialogMarkup();
    }
    dlgTemp.dialog({
        autoOpen: false,
        modal: Modal,
        show: 'clip', hide: 'clip',
        width: w, height: h, position: 'center',
        title: titleCaption, resizable: false,
        zIndex: 60,
        bgiframe: true,
        close: function(event, ui) {
            //clear dialog on close
            if (autoDIV) {
                clearDialogMarkup("div#" + dlg);
            }
            //calback
            if (closeCallback) { eval(closeCallback) }
            //scroll to last position
            $(".ui-layout-center:first").scrollTop(lastScroll);
            //fix ---del validate div
			$(".formErrorContent").parent().remove();
			//
			
        },
        open: function(event, ui) {
            $(this).html('<div class="openPage"><img src="' + CDNname + 'images/loading.gif" alt="loading" align="absmiddle"/>Opening page please wait...</div>').load(url, function() {
                $(this).hide().fadeIn(1000).css({ 'overflow': 'auto' });
                //fixIECorner();
                if (openCallback) { eval(openCallback) }
            });

        }
    });
    dlgTemp.dialog('open');
}

//test
function openIframeDlg(dlg, titleCaption, w, h, url, Modal, autoDIV, closeOther, closeCallback, openCallback) {
	if(autoDIV){
		if($("body").find("div#"+dlg).size() == 0){
		$("body").append('<div id="'+dlg+'"></div>');
	}
	}
    var dlgTemp = $('#' + dlg);
    if (!Modal) {
        Modal = false;
    }
    //clear all
    if (closeOther) {
        clearAllDialogMarkup();
    }
    dlgTemp.dialog({
        autoOpen: false,
        modal: Modal,
		show:'scale',hide:'scale',
        width: w, height: h, position: 'center',
        title: titleCaption, resizable: false,
        zIndex: 60,
        bgiframe: true,
		close: function(event, ui) { 
			//clear dialog on close
			if(autoDIV){
				clearDialogMarkup("div#"+dlg); 
			} 
			//calback
			if(closeCallback){eval(closeCallback)}
		},
		open: function(event, ui) { 
			$(this).html('<iframe src='+url+' width="100%" height="100%" frameborder="0" scrolling="no"><iframe>');
			if(openCallback){eval(openCallback)}
	
		}
   });
    dlgTemp.dialog('open');
}
//end test

function closeDlgFrame(dlg) {
    var dlgTemp = $('#' + dlg);
    dlgTemp.dialog('close');
}

/*pane maker*/
function openInPane(holder, url, pane, panSize, tips) {
    //pane = 'north' or 'south' or 'east' or west ** hide position
    //panSize = size when toggle show
    //tips = Message tell where are hide pane
    //alert(innerLayout)
    if (innerLayout == null) {
        if (!tips) {
            tips = "Toggle Show"
        }
        $(holder).wrapInner('<div class="ui-layout-' + pane + ' ui-state-default"></div>').append('<div class="ui-layout-center ui-state-default" id="paneDetailHolder" style="border:none!important"></div>');
        // innerLayout is INSIDE the center-pane of the outerLayout
        layoutSettings_Inner = {
            togglerLength_open: 20,
            togglerAlign_open: "center",
            togglerLength_closed: 20,
            togglerAlign_closed: "center",
            spacing_open: 4,
            spacing_closed: 10,
            fxName: "slide", fxSettings: { duration: 500 }

        }
        $(holder).height($(window).height() - 2)
        innerLayout = $(holder).layout(layoutSettings_Inner);
        //innerLayout.sizePane(pane, panSize);	
    }
	//clear dialog
	clearAllDialogMarkup();
	$("#paneDetailHolder").show();
    $("#paneDetailHolder").html('<div class="openPage"><img src="'+CDNname+'images/loading.gif" alt="loading" align="absmiddle"/>Opening page please wait...</div>').load(url, function() {
		innerLayout.sizePane(pane, panSize);																																									
        innerLayout.close(pane);
        $(".ui-layout-resizer-" + pane + " .ui-layout-toggler").toolTipsTw({ mes: tips, tipName: "ToggleList", showTime: 5000 });
    });


}

//*closePane*//
function closePane(holder){
	$(holder).hide().find("div.ui-layout-center, span.ui-layout-resizer ").remove();
	$(holder +" div:eq(0)").children().insertBefore($(holder +" div:eq(0)"));
	$(holder).find(".ui-layout-pane").remove();
	$(holder).slideDown(1000);
	innerLayout = null;
}


//////section maker
function makeSection(holder,active, onlyOne, sortAble) {
	if (!holder) { holder = "ui-tw-section"; }
	if (!active && active != 0) { active = false; }
	if (!sortAble) { sortAble = false; }
	if ($(holder).find("div.section").size() == 0) {
        alert("Mark up section ไม่ถูกต้อง")
    } else {
        $(holder).find("div.section").each(function(i) {
													
            if ($(this).attr("section") != "done") {
                $(this).attr("section", "done").find("div:first").addClass("ui-tw-sectionHeader ui-state-active ui-helper-clearfix ui-corner-all").next("div").addClass("ui-tw-sectionDetail ui-widget ui-widget-content");
				
                $(this).find('div.ui-tw-sectionHeader:not([airrow=done])').attr("airrow", "done").prepend('<span class="ui-icon ui-icon-grip-dotted-vertical"></span><span class="ui-icon ui-icon-triangle-1-e"></span>').disableSelection();
                $(this).find('div.ui-tw-sectionHeader:last').click(function() {

                    if (onlyOne) {// open only one section in time
                        $(holder).find("div.ui-tw-sectionDetail").slideUp('normal');
                        $(holder).find('.ui-tw-sectionHeader').removeClass("ui-corner-top").addClass("ui-corner-all").find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
                    };

                    $(this).next("div.ui-tw-sectionDetail").slideToggle('normal');

                    if ($(this).find(".ui-icon-triangle-1-e").size() > 0) {
                        $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
						$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                    } else {
                        $(this).find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
						$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                    };
					

                    return false;

                }).next("div.ui-tw-sectionDetail").css('margin-top', -1).hide();

               
            }
			
        });
		
		if (active != "all") {
			$(holder).find(".section:eq(" + active + ") .ui-tw-sectionHeader:first").click(); //active section
		} else if (active == "all") {
			$(holder).find(".ui-tw-sectionHeader").click(); //active section
		}

		if (sortAble) {//sortable section
			$(holder).sortable({ items: '.section', handle: '.ui-icon-grip-dotted-vertical', cursor: 'move' }); //require jquery.ui
			$(holder).find(".ui-icon-grip-dotted-vertical").css("cursor","move");
		};
    }
	
}

/// helper //
////
function disableEnterForm(){
	  $("form").live("keydown",function(e){//ignore enter form
		  var e_k = e.keyCode
		  if (e_k == 13){
			  return false;
		  }
	  });
}


//find all paddingSize in horizon
function horizonPaddingSize(obj) {
    var paddingLeft = $(obj).css('padding-left');
    var paddingRight = $(obj).css('padding-right');
    var thisPadding = Number(paddingLeft.substring(0, paddingLeft.length - 2)) + Number(paddingRight.substring(0, paddingRight.length - 2));

    return Number(thisPadding);
}

///clear this markup
function clearDialogMarkup(dlg) {
	$(dlg).parent().remove().end().remove();
	
}

//clear dialog markup
function clearAllDialogMarkup() {
	$("body").find("div[role=dialog]").html("").remove();
}

//assign class to <table>
function AssignTableClass(holder, makeHover, emptyCaption) {
    //clear Alpha
    $(holder).find("td").removeAttr('style');
    //empty row
    if (!$(holder).find("tbody tr").size()) {
        if (!emptyCaption) { emptyCaption = "Empty Data" }
        //find colspan size
        var colspansize = 0;
        $(holder).find("thead tr:first th").each(function() {
            colspansize = colspansize + Number($(this).attr('colspan') - 1);
        });
        var thisColspan = Number($(holder).find("thead tr:first th").size() + colspansize);
        $(holder).find("tbody").append('<tr class="emptyRow"><td align="center" style="height:50px" colspan="' + thisColspan + '">' + emptyCaption + '</td></tr>')
    }
    //addclass
	$(holder).addClass("ui-tw-gridTable ui-widget ui-corner-all ui-widget-content").attr({ border: 0, cellspacing: 1, cellpadding: 2 })//.css({"word-break": "break-all"})//.css({ 'white-space': 'nowrap' })
	.find("th").addClass("ui-widget-header")
	.end().find("td").addClass("ui-state-default")
	.end().find("tr:even td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });
	
    //hover
    if (makeHover) {
        $(holder).find("tbody tr").hover(
		  function() {
		      $(this).find("td").addClass("ui-state-focus");
		  }, function() {
		      $(this).find("td").removeClass("ui-state-focus");
		  }
		);
    }
};

//assign cutText function 
function AssignCutText(holder){
	$(holder).each(function(){
		$(this).html('<div class="doCutText" title="'+$.trim($(this).text())+'" style="overflow: hidden;text-overflow: ellipsis;-o-text-overflow: ellipsis;white-space: nowrap; width:'+$(this).attr("width")+'px">'+$.trim($(this).text())+'</div>');
	});
	
}

//make Sorting table
function sortingTable(holder){
	$(holder).each(function(){
		var thisTable = $(this);
		$(this).find("thead th").css({ cursor: 'pointer' });
		$(this).find("thead th").each(function(i) {
			//sorting with no input
			if ($(this).find("input").size() == 0) {
				$(this).toggle(function() {
					var tmpSort = [];
					var thisIndex = i;
					$(thisTable).find('tbody tr').each(function(j) {
						tmpSort.push($(thisTable).find('tbody tr:eq(' + j + ') td:eq(' + thisIndex + ')').text());
					});
					tmpSort.sort();
					//alert(tmpSort);
					$(tmpSort).each(function(k) {// map td text 
						$(thisTable).find('tbody tr').find('td:eq(' + thisIndex + ')').each(function() {
							var lookAtRow = $(this);
							//alert(tmpSort[k]+":"+$(lookAtRow).text());
							if ($(lookAtRow).text() == tmpSort[k]) {//move to top
								//alert($(this).parents("tr").text());
								var newRow = $(lookAtRow).parent().clone(true);
								$(lookAtRow).parent().remove()
								$(thisTable).find("tbody").append(newRow);
							}
						});
					});
					//$(this).find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-s");
					$(thisTable).find("tbody tr:not('.inputRow') td").removeAttr("style");
					$(thisTable).find("tbody tr:even td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

				}, function() {// toggle sort
					var tmpSort = [];
					var thisIndex = i;

					$(thisTable).find('tbody tr').each(function(j) {
						tmpSort.push($(thisTable).find('tbody tr:eq(' + j + ') td:eq(' + thisIndex + ')').text());
					});
					tmpSort.sort();
					tmpSort.reverse();
					//alert(tmpSort)
					$(tmpSort).each(function(k) {// map td text 
						$(thisTable).find('tbody tr').find('td:eq(' + thisIndex + ')').each(function() {
							var lookAtRow = $(this);
							//alert(tmpSort[k]+":"+$(lookAtRow).text());
							if ($(lookAtRow).text() == tmpSort[k]) {//move to top
								//alert($(this).parents("tr").text());
								var newRow = $(lookAtRow).parent().clone(true);
								$(lookAtRow).parent().remove();
								$(thisTable).find("tbody").append(newRow);
							}
						});
					});
					//$(this).find(".ui-icon").removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s");
					$(thisTable).find("tbody tr:not('.inputRow') td").removeAttr("style");
					$(thisTable).find("tbody tr:odd td").css({ opacity: .90, filter: 'Alpha(Opacity=90)' });

				});
				//sort icon
				$(this).hover(function() {
					if (!$(this).find(".ui-icon").size()) {
						$(this).wrapInner('<div class="caption"></div>')
						.prepend('<div style="float:right;" class="ui-icon ui-icon-triangle-1-n">');
					} else {
						$(this).find(".ui-icon").show();
					}
				}, function() {
					var tmpText = $(this).text();
					$(this).find(".caption").remove();
					$(this).text(tmpText);
					$(this).find(".ui-icon").hide();
				});
				//
			}
			//end no input
		});
		//end th each
	})
	//end each
}

// make input or text area to token list gmail stlye
function makeTokenList(selector, removeFunc, notRemove, hideInput) {
    //
    $(selector).attr("disabled", "disabled");
    //
    if ($(selector).val()) {

        $(selector).hide().next('div.' + $(selector).attr("id") + $(selector).attr("name")).remove();
        $(selector).after('<div class="tokenHolder ' + $(selector).attr("id") + $(selector).attr("name") + ' ui-helper-clearfix" style="float:left; margin:0; padding:2px; height:auto!important; background-color:#FFFFFF; border:solid 1px #666666"></div>');
        var thisArray = $(selector).val().split(",");
        var thisDiv = $(selector).next("div.tokenHolder");
        thisDiv.addClass($(selector).attr("class"));

        $(thisArray).each(function(i) {
            thisDiv.append('<span class="ui-state-active ui-corner-all" style="float:left; margin:1px; padding:1px 2px 2px 5px; white-space:nowrap; display:block"><span style="float:left; padding:2px">' + thisArray[i] + '</span><span class="ui-icon ui-icon-close removeTokenList" style="float:inherit; cursor:pointer" title="Click to remove item" index="' + i + '"></span></span>');
        });

        if (!notRemove) {
				
            thisDiv.find("span").click(function(e) { e.stopPropagation(); e.cancelBubble = true; });

            thisDiv.find("span.removeTokenList").click(function(e) {
                //
                e.stopPropagation(); e.cancelBubble = true;
                var removeItem = $(this).parent().text();
                var removeIdex = $(this).attr("index");
				
				//remove function
                if (removeFunc) {
                    //eval(removeFunc + "('" + removeIdex + "','" + removeItem + "','" + $(selector).attr("name") + "')");
                    if (eval(removeFunc + "('" + removeIdex + "','" + removeItem + "','" + $(selector).attr("name") + "')")) {
                        //remove token
                        $(this).parent().remove();
                    } else {
                        return false;
                    }
                }
				
                var groupOfVal = $(selector).val().replace(removeItem, "");

                //remove ","  and reindex value
                if (groupOfVal.charAt(0) == ",") {
                    groupOfVal = groupOfVal.substr(1);
                } else if (groupOfVal.charAt(groupOfVal.length - 1) == ",") {
                    //alert(groupOfVal.length);
                    groupOfVal = groupOfVal.substr(0, groupOfVal.length - 1);
                }
                if (groupOfVal.split(",,").length > 0) {
                    groupOfVal = groupOfVal.replace(",,", ",");
                }
                //reindex value
                $(selector).val(groupOfVal);
                /*//remove function
                if (removeFunc) {
                    eval(removeFunc + "('" + removeIdex + "','" + removeItem + "','" + $(selector).attr("name") + "')");
                }
                //remove token
                $(this).parent().remove();*/
                //if no val
                if ($(selector).val() == "") {
                    $(selector).attr("disabled", "disabled").next("div.tokenHolder").remove();
                    if (!hideInput) {
                        $(selector).show();
                    }
                }
                //
            });
        } else {
            thisDiv.find("span.removeTokenList").remove();
        }
        thisDiv.click(function() { $(selector).click() });
    } else {
        $(selector).show().attr("disabled", "disabled").next("div.tokenHolder").remove();
    }
}

//
function scrollAbleTable(holder, h, tdmaping, footerFix) {
    
	//var divSize = "100%";
	var overflowDiv = "hidden";
	var hsize= h.substring(0,h.length-2);
	var barSize = 0;
	//
	if($(holder).find("tbody").height() > hsize){
		//alert(hsize);
	    if (!$.browser.msie) { barSize = 16; }
		//divSize = ($(holder).width()+barSize)+"px";
		overflowDiv = "auto";
	
		//
		if(!tdmaping){tdmaping = 0;}
		//--------header----------
		$(holder).wrap('<div style="padding-right:' + barSize + 'px"><div class="scrollAbleTable" style="height:' + h + '; width:100%; overflow-y:' + overflowDiv + '; overflow-x:hidden"></div></div>');
		$(holder).parent().before($(holder).clone(true)).prev().removeAttr("id").find("tbody, tfoot").remove();
		var header = $(holder).parent().prev();
		//
		$(holder).find("thead").hide();
		//fix multi row header
		$(header).find("thead tr th").each(function() {
			if (Number($(this).attr("colspan")) > 1) {
				$(this).attr("ignore", "ignore");
				//alert();
				//ignoreTh = ignoreTh+1
			}
		});
		//
		$(header).find("thead tr th:not([ignore])").each(function(i){
			$(this).width($(holder).find("tbody tr:eq("+tdmaping+") td").eq(i).width());
		});
		//-------footer----------
		if(footerFix){
			$(holder).parent().after($(holder).clone(true)).next().removeAttr("id").find("tbody, thead").remove();
			var footer = $(holder).parent().next();
			$(holder).find("tfoot").hide();
			//fix footer sum column
			var footColumn = 0;
			$(footer).find("th").each(function(){
				if($(this).attr("colspan")){
					footColumn = Number(footColumn+$(this).attr("colspan"));
				}			   
			});
			footColumn=footColumn-1;
			//
			$(footer).find("tfoot tr:first th:not([colspan]), tfoot tr:first td:not([colspan])").each(function(i){
				$(this).width($(holder).find("tbody tr:eq("+tdmaping+") td").eq(i+footColumn).width());
			});
		}
		//fix resize
		$(holder).parent().width($(header).width()+barSize);
		$(window).resize(function() {
			$(holder).parent().width($(header).width() + barSize);
		});
	}
}

//by meay
function timeStamp(inputTarget){
	$(inputTarget).click(function(e){
		e.stopPropagation(); e.cancelBubble = true;						   
		var timeData = ["00:00","00:30","01:00","01:30","02:00","02:30","03:00","03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","08:00","08:30","09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30","20:00","20:30","21:00","21:30","22:00","22:30","23:00","23:30"];
		$(this).next("ul").remove();
		var thisInput = $(this);
		$(this).after('<ul role="timestamp" style="position:absolute;z-index:300"></ul>');			   

		var nextTime = $(this).next();
		var xposition = $(this).position().left;
		var yposition = $(this).position().top+$(this).outerHeight()-12;
		$(nextTime).hide().addClass("ui-widget").css({"list-style":"none","list-style":"none","cursor":"pointer","padding-left":"0px","width":"70px","overflow":"auto","height":"150px","border":"solid 1px gray","background-color":"#FFF","left":xposition+"px","top":yposition+"px"})
		$(timeData).each(function(i){
			$(nextTime).append("<li>"+timeData[i]+"</li>")
		});
		
		$(nextTime).slideDown().find("li").click(function(e){
			e.stopPropagation(); e.cancelBubble = true;												  
			var list = $(this).text(); 
			$(thisInput).val(list);
			$(nextTime).slideUp();						   
		});
		
	}).keydown(function(){
		return false;	
	});
	
	$(document).click(function(){
		$("ul[role=timestamp]").slideUp();
	});
}